import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Radio,DatePicker }from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import ExecuteChargeModal from '../common/ExecuteChargeModal';
import RemarkModal from '../common/RemarkModal';
import {
  ASSET_LEVEL
} from "../constants/index";
import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker;


export default class WaitingBuybackList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           searchFlag:true,
           visible:false,
           resetpwdId:null,
           selectedRowKeys:[],
           currentSelectedRecord:{},
           session:{},

        };
    }

     componentWillMount(){
      let {page,pageSize} = this.state
      this.doFetch(page,pageSize);
    }
    componentWillReceiveProps(nextProps){
      // let session =  this.props.route.session;
      //   this.setState({
      //     session
      // })
    }
    //查询列表
    async doFetch(page,size,searchCondition={}){

      this.setState({
        searchFlag:true
      })
      let session =  this.props.route.session;
      let {keyword} = this.state.search
      let asset_status = "";
      asset_status = "WAIT_TO_BUY_BACK";
      
      let result = await api('/assets/asset/list',{pageNumber:page,pageSize:size,asset_status:asset_status,keyword:keyword,list_type:"NORMAL",...searchCondition});
      if(result.success){
          this.setState({
            total:result.data.totalItem,
            list:result.data.pageResult||[],
            page,
            searchFlag:false,
            pageSize:result.data.pageSize,
            session,
          });
      }else{
        this.setState({
          searchFlag:false,
          session,
        })
        message.error(result.message)
      }

    }

    doSearch(){
      let {page,pageSize} = this.state;
      this.doFetch(page,pageSize);
    }








    onSearch(searchCondition){
      let {search} = this.state;
      search = {...searchCondition}
      this.setState({
        search,
        filterConditionVisibility:false
      })

      this.doFetch(1,10,searchCondition)
    }

    onReset(){
      this.setState({
        search:{},
        filterConditionVisibility:false
      })
    }

    exportTable(e){
      if (e.key == "ALL") {
        
      }else if (e.key == "SELECTED") {
        
      }else{

      }
    }

    onSearchKeyWords(){

    }

    onSelectRows(selectedRowKeys, selectedRows){


       this.setState({
        selectedRowKeys,
        selectedRows,
       })
    }

    //点击确认弹窗按钮
    onClickBuyBackOk(){
      let {isBatch} = this.state;
      if (isBatch) {
        this.batchSubmitRedeem();
      }else{
        this.onSubmitRedeem();
      }
    }

    //点击确认赎回弹窗上的确定按钮
    async onSubmitRedeem(){
      this.setState({
        searchFlag:true,
      })
      let {session,currentSelectedRecord,list,page,pageSize} = this.state;
      let assetStatusType = "";
      if (session.role_type == "ORIGINATOR") {//取消回购
        assetStatusType = "IN_POOL";
      }else{
        assetStatusType = "RECOVERED";
      }
      let asset_id_list = [currentSelectedRecord.id];
      let result = await api("/assets/submit",{assetStatusType,asset_id_list});
      if (result.success) {
        message.success("提交成功！");
        if (list.length == 1 && page > 1) {
          page = page -1 ;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message)
      }


      this.setState({
        confirmBuybackVisibility:false,
        searchFlag:false,
      })
    }

    async batchSubmitRedeem(){
      this.setState({
        searchFlag:true,
      })
      let {session,selectedRows,list,page,pageSize} = this.state;
      let assetStatusType = "";
      if (session.role_type == "ORIGINATOR") {//取消回购
        assetStatusType = "IN_POOL";
      }else{
        assetStatusType = "RECOVERED";
      }
      let asset_id_list = [];
      selectedRows.map((record,index) => {
        asset_id_list.push(record.id);
      })
      let result = await api("/assets/submit",{assetStatusType,asset_id_list});
      if (result.success) {
        message.success("提交成功！");
        if (list.length == 1 && page > 1) {
          page = page -1 ;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message)
      }


      this.setState({
        confirmBuybackVisibility:false,
        searchFlag:false,
      })
    }

    onSubmitExecuteCharge(params){
      let {executeChargeContent} = this.state;
      executeChargeContent = {...params};
      this.setState({
        executeChargeContent,
        executeChargeVisibility:false,
      })
    }

    onCancelExecuteChargeModal(){
      this.setState({
        executeChargeVisibility:false,
      })
    }


    //提交备注
    onSubmitRemark(params){
      this.saveRemark(params);
    }

    //提交备注
    async saveRemark(values) {
      let {currentSelectedRecord} = this.state;
      values.asset_id = currentSelectedRecord.id;
      let result = await api('/assets/remark/edit' ,values);
      if(!result.success){
        message.error(result.message);
        return
      }

      message.success('保存成功' , 1, () => {
        this.setState({remarkVisibility:false},() =>{
          this.doFetch()
        })
      })
    }

    onCancelRemarkModal(){
      this.setState({
        remarkVisibility:false,
      })
    }


    getTableHeader(){
      let {selectedRowKeys,pageSize,session} = this.state;
      if (selectedRowKeys.length > 0 ) {
        return(
            <div className="table-header">
              <p className="table-header-content" > 
                已选中{selectedRowKeys.length}/{pageSize}
                <span className="marginR10 marginL10">|</span>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    this.setState({
                        confirmBuybackVisibility:true,
                        isBatch:true,
                      })
                  }}
                > 
                  { session.role_type == "ORIGINATOR"?
                    <span>取消回购</span>
                  :
                    <span>同意回购</span>
                  }
                </Button>
                <Button
                  type="primary"
                  className="marginL10"
                  size="small"
                >导出选中</Button>
               </p>
            </div>
          )
      }else{
        return(
            <div className="table-header">
              <span className="table-header-content">已选中0/{pageSize}</span>
            </div>
          )
      }
    }




    //分页
    toPage({current:page,pageSize,total}){
      this.doFetch(page,pageSize);
    }

    getExportMenu(){
      return (
          <Menu onClick={this.exportTable.bind(this)}>
            <Menu.Item key="ALL">导出全部</Menu.Item>
            <Menu.Item key="SELECTED">导出选中</Menu.Item>
          </Menu>
        )
    }
    
    render() {

        var {list, page,total,searchFlag,departmentList,search,pageSize,selectedRowKeys,session}=this.state;
        return (
            <div >
                {/*<NavBar navs={[{title:'社区信息'}]} />*/}
                <ContentBody className='container'>
                  <div>
                      <div style={{"float":"left"}}>待回购资产</div>
                      <div>
                      <div className="text-right">
                        <Button
                          type="primary"
                          onClick={() => {
                            this.setState({
                              filterConditionVisibility:true,
                            })
                          }}
                          className="marginR10"
                          >筛选</Button>

                          <Dropdown 
                              overlay={this.getExportMenu()}
                              >
                            <Button
                              className='marginR10'
                            >导出<Icon type="down" /></Button>
                          </Dropdown>
                        

                        <Input
                            {...this::bind_change('keyword')}
                            placeholder="搜索关键字"
                            style={{"width":"120px"}}
                            className='marginR10'
                          />

                        <Button
                          type="primary"
                          icon="search"
                          onChange={this.onSearchKeyWords.bind(this)}
                        >搜索</Button>
                      </div>

                        
                      </div>
                  </div>

                  <Table
                    bordered
                    title={this.getTableHeader.bind(this)}
                    columns={this.getColumns()}
                    simple
                    dataSource={list}
                    pagination={{
                      current:page,
                      total:total,
                      pageSize:pageSize,

                    }}
                    loading={searchFlag}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                    rowSelection={{
                      onChange:this.onSelectRows.bind(this),
                      selectedRowKeys,
                    }}
                    className='marginT20'
                  />

                  <SearchPanel
                    visibility = {this.state.filterConditionVisibility}
                    onSearch = {this.onSearch.bind(this)}
                    onReset = {this.onReset.bind(this)}
                  />

                    <Modal
                      title="提示"
                      visible={this.state.confirmBuybackVisibility}
                      onOk={this.onClickBuyBackOk.bind(this)}
                      onCancel={() => {
                        this.setState({
                          confirmBuybackVisibility:false,
                        })
                      }}
                    > {session.role_type == "ORIGINATOR" ?
                        <p>确定要放弃回购已选中的资产？</p>
                        :
                        <p>确定同意债权人回购该资产?</p>
                        
                      }
                    </Modal>
                  

                  <ExecuteChargeModal
                    visibility = {this.state.executeChargeVisibility}
                    onSubmitExecuteCharge = {this.onSubmitExecuteCharge.bind(this)}
                    onCancelExecuteChargeModal = {this.onCancelExecuteChargeModal.bind(this)}
                  >
                  </ExecuteChargeModal>

                  <RemarkModal
                    visibility = {this.state.remarkVisibility}
                    onSubmitRemark = {this.onSubmitRemark.bind(this)}
                    onCancelRemarkModal = {this.onCancelRemarkModal.bind(this)}
                    userType={session.role_type}
                  >
                  </RemarkModal>

                </ContentBody>
            </div>
        );
    }

    getColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '债务人',
              dataIndex: 'debtor',
              key: 'debtor',
            }, {
              title: '应收账款日',
              dataIndex: 'start_date',
              key: 'start_date',
            },{
              title: '分级',
              dataIndex: 'level',
              key: 'level',
              render:(level) => {
                return ASSET_LEVEL[level];
              }
            }, {
              title: '应收总金额',
              dataIndex: 'money_sum',
              key: 'money_sum',
            },{
              title: '当前余额',
              dataIndex: 'money_left',
              key: 'money_left'
            },{
              title: '预计收款日',
              dataIndex: 'predict_date',
              key: 'predict_date'
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:220,
              render: (record) =>{
                if(!record.id) return;
                  return (
                        <span className={'table-operation'}>
                            <span>
                              <a
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.context.router.push(`/underlyingAssets/propertyData/Detail?id=${record.id}`)
                                }}
                              >
                                查看
                              </a>
                              <i className='separator'>|</i>
                            
                              <a 
                                href='javascript:void 0'
                                onClick = {() =>{
                                  this.setState({
                                    currentSelectedRecord:record,
                                    confirmBuybackVisibility:true,
                                  })
                                }}
                              >
                                {session.role_type == "ORIGINATOR"?
                                  <span>取消回购</span>
                                :
                                  <span>同意回购</span>
                                }
                              </a>
                              
                              <i className='separator'>|</i>
                              <a
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.setState({
                                    currentSelectedRecord:record,
                                    remarkVisibility:true
                                  })
                                }}
                              >
                                备注说明
                              </a>
                            </span>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}
WaitingBuybackList.contextTypes= { router: React.PropTypes.object.isRequired};
